package com.miaoshare.core.base;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.app.PictureAppMaster;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.entity.MediaExtraInfo;
import com.luck.picture.lib.immersive.ImmersiveManager;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.luck.picture.lib.style.PictureSelectorStyle;
import com.luck.picture.lib.style.SelectMainStyle;
import com.luck.picture.lib.utils.MediaUtils;
import com.miaoshare.core.utils.AppManager;
import com.miaoshare.core.utils.GlideEngine;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import demo.ywd.com.listenerlibrary.NetworkListener;

/**
 * Created by HeroSun
 * date 2022-01-12
 **/
public abstract class BaseActivity<P extends BasePresenter> extends AppCompatActivity implements BaseView {

    /**
     * 是否注册事件分发，默认不绑定
     */
    protected boolean isRegisterEventBus() {
        return false;
    }

    /**
     * 是否设置沉浸式状态栏
     */
    protected boolean isSetImmersionBar() {
        return false;
    }

    private Unbinder mUnbinder = null;

    private final String TAG = getClass().getName();
    public BaseActivity mCounent;
    public P presenter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mCounent = this;
        if (isSetImmersionBar()) {
//            mImmersionBar = ImmersionBar.with(this);
            ImmersionBar.with(this)
                    .statusBarColor(android.R.color.white)
                    .statusBarDarkFont(true)   //状态栏字体是深色，不写默认为亮色
                    .flymeOSStatusBarFontColor(android.R.color.black)
                    .fitsSystemWindows(true)
                    .navigationBarColor(android.R.color.white)
                    .autoNavigationBarDarkModeEnable(true, 0.2f)
                    .init();
        }

        if (isRegisterEventBus()) {
            EventBus.getDefault().register(this);
        }

        setContentView(getLayoutId());
        mUnbinder = ButterKnife.bind(this);

        presenter = initPresenter();
        if (presenter != null) {
            presenter.attach(this);
        }
        AppManager.getAppManager().addActivity(this);
        initView();
        loadData();
        //  注册网络监听
        NetworkListener.getInstance().registerObserver(this);
    }

    @Override
    protected void onDestroy() {
        if (isRegisterEventBus()) {
            EventBus.getDefault().unregister(this);
        }
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
        NetworkListener.getInstance().unRegisterObserver(this);

        if (presenter != null) {
            presenter.detach();
        }
        super.onDestroy();
        AppManager.getAppManager().finishActivity(this);
    }


    /**
     * 获取布局资源文件
     */
    protected abstract int getLayoutId();

    /**
     * 初始化控件
     */
    protected abstract void initView();

    /**
     * 绑定数据
     */
    protected abstract void loadData();


    /**
     * 初始化presenter
     */
    @Nullable
    protected abstract P initPresenter();

    @Override
    public void showLoadingDialog() {
//        if (mLoadingDialog == null) {
//            mLoadingDialog = LoadingDialog.with(getContext());
//        }
//        mLoadingDialog.show();
    }

    @Override
    public void dismissLoadingDialog() {
//        if (mLoadingDialog != null) {
//            mLoadingDialog.dismiss();
//        }
    }

    @Override
    public void showLoadingBar() {
    }

    @Override
    public void dismissLoadingBar() {
    }

    @Override
    public void clearLoading() {
//        if (mLoadingDialog != null) {
//            mLoadingDialog.clear();
//        }
//        mLoadingDialog = null;
    }

    @Override
    public Context getContext() {
        return getActivity();
    }

    protected Activity getActivity() {
        return this;
    }

    /**
     * 选择图片-摄像头
     */
    protected void selectImageCamera() {
        // 单独拍照
        PictureSelector.create(this)
                .openCamera(SelectMimeType.ofAll())
                .isOriginalControl(true)
                .isCameraForegroundService(false)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        setTranslucentStatusBar();
                        analyticalSelectResults(result);
                    }

                    @Override
                    public void onCancel() {
                        setTranslucentStatusBar();
                        Log.i(TAG, "PictureSelector Cancel");
                    }
                });

    }

    /**
     * 选择图片-图库
     *
     * @param maxCount 最大选择数量
     */
    protected void selectImageGallery(int maxCount) {
        SelectMainStyle selectMainStyle = new SelectMainStyle();
        selectMainStyle.setDarkStatusBarBlack(false);
        PictureSelectorStyle pictureSelectorStyle = new PictureSelectorStyle();
        pictureSelectorStyle.setSelectMainStyle(selectMainStyle);
        // 进入相册
        PictureSelector.create(getContext())
                .openGallery(SelectMimeType.ofImage())
                .setImageEngine(GlideEngine.createGlideEngine())
                .isCameraForegroundService(false)
                .setSelectorUIStyle(pictureSelectorStyle)
                .setMaxSelectNum(maxCount)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
//                        setTranslucentStatusBar();
                        analyticalSelectResults(result);
                    }

                    @Override
                    public void onCancel() {
//                        setTranslucentStatusBar();
                        Log.i(TAG, "PictureSelector Cancel");
                    }
                });
        // 方式二
//        PictureSelectorFragment selectorFragment = PictureSelector.create(v.getContext())
//                .openGallery(SelectMimeType.ofAll())
//                .setImageEngine(GlideEngine.createGlideEngine())
//                .build();
//        getSupportFragmentManager().beginTransaction()
//                .add(R.id.fragment_container, selectorFragment, selectorFragment.getFragmentTag())
//                .addToBackStack(selectorFragment.getFragmentTag())
//                .commitAllowingStateLoss();;
    }


    /**
     * 选择视频-摄像头
     */
    protected void selectVideoCamera() {
        PictureSelector.create(this)
                .openCamera(SelectMimeType.ofVideo())
                .isOriginalControl(true)
                .isCameraForegroundService(false)
                .setRecordVideoMaxSecond(30)
                .setRecordVideoMinSecond(1)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
//                        setTranslucentStatusBar();
                        analyticalSelectResults(result);
                    }

                    @Override
                    public void onCancel() {
//                        setTranslucentStatusBar();
                        Log.i(TAG, "PictureSelector Cancel");
                    }
                });
    }

    /**
     * 选择视频-图库
     *
     * @param maxCount 最大选择数量
     */
    protected void selectVideoGallery(int maxCount) {
        PictureSelector.create(getContext())
                .openGallery(SelectMimeType.ofVideo())
                .setMaxSelectNum(maxCount)
                .isCameraForegroundService(false)
                .setMinSelectNum(1)
                .setSelectionMode(maxCount > 1 ? SelectModeConfig.MULTIPLE : SelectModeConfig.SINGLE)
                .setRecordVideoMaxSecond(30)
                .setRecordVideoMinSecond(1)
                .setSelectMaxDurationSecond(30)
                .setImageEngine(GlideEngine.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
//                        setTranslucentStatusBar();
                        analyticalSelectResults(result);
                    }

                    @Override
                    public void onCancel() {
//                        setTranslucentStatusBar();
                        Log.i(TAG, "PictureSelector Cancel");
                    }
                });
    }

//    @Override
//    public void onSelectFinish(PictureCommonFragment.SelectorResult result) {
////        setTranslucentStatusBar();
//        if (result == null) {
//            return;
//        }
//        if (result.mResultCode == RESULT_OK) {
//            ArrayList<LocalMedia> selectorResult = PictureSelector.obtainSelectorList(result.mResultData);
////            analyticalSelectResults(selectorResult);
//        } else if (result.mResultCode == RESULT_CANCELED) {
//            Log.i(TAG, "onSelectFinish PictureSelector Cancel");
////            setTranslucentStatusBar();
//        }
//    }

    /**
     * 处理选择结果
     *
     * @param result
     */
    protected ArrayList<LocalMedia> analyticalSelectResults(ArrayList<LocalMedia> result) {
        StringBuilder builder = new StringBuilder();
        builder.append("Result").append("\n");
        for (LocalMedia media : result) {
            if (media.getWidth() == 0 || media.getHeight() == 0) {
                if (PictureMimeType.isHasImage(media.getMimeType())) {
                    MediaExtraInfo imageExtraInfo = MediaUtils.getImageSize(media.getPath());
                    media.setWidth(imageExtraInfo.getWidth());
                    media.setHeight(imageExtraInfo.getHeight());
                } else if (PictureMimeType.isHasVideo(media.getMimeType())) {
                    MediaExtraInfo videoExtraInfo = MediaUtils.getVideoSize(PictureAppMaster.getInstance().getAppContext(), media.getPath());
                    media.setWidth(videoExtraInfo.getWidth());
                    media.setHeight(videoExtraInfo.getHeight());
                }
            }
            builder.append(media.getAvailablePath()).append("\n");
            Log.i(TAG, "文件名: " + media.getFileName());
            Log.i(TAG, "是否压缩:" + media.isCompressed());
            Log.i(TAG, "压缩:" + media.getCompressPath());
            Log.i(TAG, "原图:" + media.getPath());
            Log.i(TAG, "绝对路径:" + media.getRealPath());
            Log.i(TAG, "是否裁剪:" + media.isCut());
            Log.i(TAG, "裁剪:" + media.getCutPath());
            Log.i(TAG, "是否开启原图:" + media.isOriginal());
            Log.i(TAG, "原图路径:" + media.getOriginalPath());
            Log.i(TAG, "沙盒路径:" + media.getSandboxPath());
            Log.i(TAG, "原始宽高: " + media.getWidth() + "x" + media.getHeight());
            Log.i(TAG, "裁剪宽高: " + media.getCropImageWidth() + "x" + media.getCropImageHeight());
            Log.i(TAG, "文件大小: " + media.getSize());
        }
        return result;
    }

    /**
     * 设置状态栏字体颜色
     */
    private void setTranslucentStatusBar() {
        ImmersiveManager.translucentStatusBar(this, true);
    }

    // 上传图片结果


    /**
     * Uri 转 绝对路径
     *
     * @param uri
     * @return
     */
    public String getFilePathByUri_BELOWAPI11(Uri uri, Context context) {
        // 以 content:// 开头的，比如  content://media/external/file/960
        if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
            String path = null;
            String[] projection = new String[]{MediaStore.Images.Media.DATA};
            Cursor cursor = context.getContentResolver().query(uri, projection, null,
                    null, null);
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    if (columnIndex > -1) {
                        path = cursor.getString(columnIndex);
                    }
                }
                cursor.close();
            }
            return path;
        }
        return null;
    }
}
